/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package adee.qrlogin;

import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import qrlogin.common.QRLoginParam;

/**
 *
 * @author adee
 */
public class Account {
   private  int id;
   private  String link;
   private String sessionId;
   private boolean modified = true;
   private int logined;
   private LoginInfo loginInfo;

    public boolean isModified() {
        return modified;
    }

    public void setModified(boolean modified) {
        this.modified = modified;
    }

    @Override
    public String toString() {
        return this.getHost()+":"+(this.logined==1?"Bejelentkezve":"Kijelentkezve");
    }


    public int isLogined() {
        return logined;
    }

    public void setLogined(int logined) {
        this.logined = logined;
    }

    public HashMap<String,QRLoginParam> getLoginParameters() {
        return loginInfo.getParams();
    }

    public void setLoginParameters(HashMap<String,QRLoginParam> loginParameters) {
        this.loginInfo.setParams(loginParameters);
    }


    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }



    public Account(String link,String sessionId) {
        this.id=-1;
        this.link = link;
        this.sessionId = sessionId;
        this.generateParameterListFromXML(this.remoteCommand("SHOW_INFO"));
    }

    public Account(int id,String link,String sessionId,int logined) {
        this.id = id;
        this.link = link;
        this.sessionId = sessionId;
        this.logined=logined;
        this.loginInfo = new LoginInfo();
    }


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    private void generateParameterListFromXML(String xml){
        this.loginInfo = new LoginInfo(xml);
    }

    private String remoteCommand(String command){
       HttpClient httpclient = new DefaultHttpClient();
       HttpGet httpget = new HttpGet(this.getLink()+"?op="+command);
       httpget.setHeader("cookie:","JSESSIONID="+this.getSessionId()+";");
       StringBuilder builder = new StringBuilder();
       try {
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
           InputStream instream = entity.getContent();
           BufferedReader reader2 = new BufferedReader(new InputStreamReader(instream));
           String line;
           while ((line=reader2.readLine())!=null){
            builder.append(line);
           }
       }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }
       return builder.toString();

    }

     private String doLogin() throws IOException {
       // Create a new HttpClient and Post Header
       List<NameValuePair> params = new ArrayList<NameValuePair>();
         for (qrlogin.common.QRLoginParam param: this.getLoginParameters().values()){
             params.add(new BasicNameValuePair(param.getName(), param.getValue()));
         }
       HttpClient httpclient = new DefaultHttpClient();
       HttpPost httppost = new HttpPost(link+"?op=DO_LOGIN");
       httppost.setHeader("cookie:","JSESSIONID="+this.getSessionId()+";");
       StringBuilder builder = new StringBuilder();
       try {
        httppost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
           InputStream instream = entity.getContent();
           BufferedReader reader2 = new BufferedReader(new InputStreamReader(instream));
           String line;

           while ((line=reader2.readLine())!=null){
            builder.append(line);
           }
       }


    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
      return builder.toString();
  }

     public String login(){
         String respond = "Nincs válasz, belépés sikertelen.";
        try {
             respond = this.doLogin();

            if (respond!=null){
                if (respond.contains("PASSED")){
                    this.setLogined(1);
                } else this.setLogined(0);
            }
        } catch (IOException ex) {
            
        }
        return respond;
     }

     public void logout(){
            String respond = this.remoteCommand("DO_LOGOUT");
            if (respond!=null){
                if (respond.equals("SUCCESS")) this.setLogined(0);
            }
           this.setSessionId("LOGOUTED_SESSION");
     }

     public void refreshStatus(){
            String respond = this.remoteCommand("IS_LOGINED");
            if (respond!=null){
                if (respond.equals("TRUE")) {
                    this.setLogined(1);
                }
                else {
                    this.setLogined(0);
                    this.setSessionId("LOGOUTED_SESSION");
                }
            } else{
                this.setLogined(0);
                this.setSessionId("LOGOUTED_SESSION");
            }
     }

     private String getHost(){

            try {
                URL url = new URL(this.getLink());
                return url.getHost();
            } catch (MalformedURLException ex) {

                return link;
            }


        }
}
